<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User_model extends CI_Model 
{    
    function __construct()
    {
        parent::__construct();
    }
    
    function get_one($uid)
    {
        $where = array(
            'uid'=>$uid
        );
        $this->db->where($where);
        return $this->db->get('users')->row_array();
    }
    
    function get_users()
    {
        return $this->db->get('users')->result_array();
    }
    
    /** 检查登录 */
    function isLogin($users)
    {
        /** 处理数据库验证 */
        $sql = "SELECT * FROM users WHERE activated=1 AND mail = ? AND password = ?";
        $quiry = $this->db->query($sql, array($users['email'], sha1(trim($users['password']))));
       
        return ($quiry->num_rows() > 0)? $quiry->row_array() : 0;
    }
    
    function add($users)
    {
        
        /** 构建插入结构 */
        $insertStruct = array(
            'created'       =>  time(),
            'mail'          =>  $users['mail'],
            'screenName'    =>  $users['screenName'],
            'group'         =>  $users['group'],
            'activated'     =>  $users['activated']
        );

        if(!empty($users['password']))
            $insertStruct['password'] = sha1($users['password']);

        if (!empty($users['uid']))
        {
            unset($insertStruct['created']);
            $this->db->where('uid', $users['uid']);
            $insertId = $this->db->update('users', $insertStruct);
        }
        else
        {
            /** 首先插入部分数据 */
            $this->db->insert('users', $insertStruct);
            $insertId = $this->db->insert_id();
        }
        return $insertId;
    }
    
    public function delete_user($uid)
    {        
        //删除 users
        return $this->db->delete('users', array('uid' => $uid));
    }
    
}